<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                   label-width="120px">
            <el-form-item label="模板类型" prop="templateType">
              <el-select v-model="queryParams.templateType" class="width-120" clearable
                         placeholder="请选择模板类型">
                <el-option v-for="dict in dictDataMap['pdf_print_template']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="queryParams.templateName" clearable placeholder="请输入模板名称"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="模板名称字符串" prop="templateCode">
              <el-input v-model="queryParams.templateCode" clearable placeholder="请输入模板名称字符串"
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <div class="mr20" style="float: right">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:printPdfTemplate:add']" plain type="primary"
                       @click="handleAdd">
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:printPdfTemplate:edit']" :disabled="single" plain type="success"
                       @click="handleUpdate">
              <template #icon>
                <i-ep-edit/>
              </template>
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:printPdfTemplate:remove']" :disabled="multiple" plain type="danger"
                       @click="handleDelete">
              <template #icon>
                <i-ep-delete/>
              </template>
              删除
            </el-button>
          </el-col>
        </el-row>
        <el-table v-adaptive :border="true" :data="printPdfTemplateList" :header-cell-style="$headerCellStyle" :stripe="true"
                  highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="55"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="模板类型"
                           prop="templateType">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['pdf_print_template']"
                             :value="scope.row.templateType"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="模板名称"
                           prop="templateName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="模板名称字符串"
                           prop="templateCode"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="模板文件存储路径"
                           prop="filePath"/>
          <!--                    <el-table-column :show-overflow-tooltip="true" label="模板下载url" :align="'center'" prop="fileUrl"/>-->
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注" prop="remark"/>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="350">
            <template #default="scope">
              <el-button v-hasPerm="['base:printPdfTemplate:edit']" type="success"
                         @click="handleUpdate(scope.row)">
                <template #icon>
                  <i-ep-edit/>
                </template>
                修改
              </el-button>
              <el-button v-hasPerm="['base:printPdfTemplate:remove']" type="danger"
                         @click="handleDelete(scope.row)">
                <template #icon>
                  <i-ep-delete/>
                </template>
                删除
              </el-button>
              <el-button type="success" @click="handleDown(scope.row)">
                <template #icon>
                  <i-ep-download/>
                </template>
                模板下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改pdf打印模板字典对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item label="模板类型" prop="templateType">
              <el-select v-model="form.templateType" placeholder="请选择模板类型" style="width: 100%"
                         @change="templateTypeChange">
                <el-option v-for="dict in dictDataMap['pdf_print_template']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板存储路径" prop="filePath">
              <el-input v-model="form.filePath" disabled
                        placeholder="不用填写，将文件上传到服务器后会自动生成路径"
                        style="margin-bottom: 10px"/>
              <el-upload ref="uploadRef" :auto-upload="false" :file-list="fileList"
                         :http-request="uploadFile" :limit="6" :on-change="handleChange"
                         :on-exceed="handleExceed" :on-preview="handlePreview" :on-remove="handleRemove"
                         accept=".jasper,.jrxml" action="http://xxx.xxx.xxx/personality/uploadExcel"
                         multiple>
                <el-button slot="trigger" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传.jasper,.jrxml文件，且不超过100m</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板名称字符串" prop="templateCode">
              <el-input v-model="form.templateCode" disabled placeholder="模板名称字符串"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板下载url" prop="fileUrl">
              <el-input v-model="form.fileUrl" disabled placeholder="请输入模板下载url"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button style="margin-left: 10px" type="success" @click="submitUpload">
                        上传到服务器
                    </el-button>
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
    <!--        打印弹出框-->
    <!-- <print-preview ref="printPreviewRef" :title="'测试打印页面'" /> -->
    <!--        <pdf-preview ref="printPreviewRef" :title="'测试打印页面'" />-->
  </div>
</template>

<script lang="ts" setup>
import {
  addPrintPdfTemplate,
  delPrintPdfTemplate,
  downloadFile,
  getPrintPdfTemplate,
  selectPagePrintPdfTemplate,
  updatePrintPdfTemplate,
  uploadPdfFile
} from "@/api/base/PrintPdfTemplate";
import {print} from '@/api/report.ts'
// import printPreview from "@/components/PrintPreview/PrintPreview.vue";
// import preview from '@/views/designer/preview.vue'
// import pdfPreview from "@/components/PrintPreview/PdfPreview.vue"
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any
const dictStore = useDictStoreHook();
const printPreviewRef = ref();
const uploadRef = ref()
const dictDataMap = ref(dictStore.isTypeGetData('pdf_print_template'))
const formRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const buttonLoading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 参数表格数据
const configList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 日期范围
const dateRange = ref([])
// pdf打印模板字典表格数据
const printPdfTemplateList = ref([])
const opens = ref(false)

const fileData = ref<any>(null)  // 文件上传数据（多文件合一）
const fileList = ref([])  // upload多文件数组
// 表单参数
const form = ref<any>({})
const objectUrl = ref("")
// 表单校验
const rules = ref({
  templateType: [
    {required: true, message: "模板类型不能为空", trigger: "change"}
  ],
  templateName: [
    {required: true, message: "模板名称不能为空", trigger: "blur"}
  ],
  templateCode: [
    {required: true, message: "模板名称代码不能为空", trigger: "blur"}
  ],
  filePath: [
    {required: true, message: "模板文件存储路径不能为空", trigger: "blur"}
  ],
})

// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  templateType: "",
  templateName: "",
  templateCode: "",
  filePath: "",
  fileUrl: "",
  orgId: "",
})
if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  getList()
}

async function printPdf(row) {
  const param = {
    pageIndex: 1,
    reportName: '号源.ureport.xml',
    content: '',
    query: {}
  }
  await print(param)
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id
  getList()
}

/** 查询pdf打印模板字典列表 */
function getList() {
  selectPagePrintPdfTemplate(queryParams.value).then((response: any) => {
    printPdfTemplateList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: "",
    templateType: "",
    templateName: "",
    templateCode: "",
    filePath: "",
    fileUrl: "",
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    remark: "",
    delFlag: "",
    orgId: queryParams.value.orgId
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  if (!queryParams.value.orgId) {
    ElMessage.error("请选择机构后再搜索");
    return
  }
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    ElMessage.error("请选择机构后再搜索");
    return
  }
  reset();
  open.value = true;
  title.value = "添加pdf打印模板";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const idThis = row.id || ids.value
  getPrintPdfTemplate(idThis).then((response: any) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改pdf打印模板";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        updatePrintPdfTemplate(form.value).then(_response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
          fileList.value = []
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addPrintPdfTemplate(form.value).then(_response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
          fileList.value = []
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idsThis = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除pdf打印模板字典编号为"' + idsThis + '"的数据项？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delPrintPdfTemplate(idsThis).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  // download('base/PrintPdfTemplate/export', {
  //     ...queryParams.value
  // }, `PrintPdfTemplate_${new Date().getTime()}.xlsx`)
}

/** 模板下载 */
function handleDown(row) {
  const link = document.createElement('a')
  const formData = new FormData()
  formData.append("id", row.id)
  let lastPathIndex = Number(row.filePath.lastIndexOf("\\") || row.filePath.lastIndexOf("/")) + 1;
  // 获取路径中最后一个.
  let lastIndex = row.filePath.lastIndexOf(".");
  form.value.templateCode = row.filePath.substring(lastPathIndex, lastIndex)
  downloadFile(formData).then(res => {
    const blob = new Blob([res.data], {type: 'application/octet-stream'})
    // $nextTick(() => {
    // 自定义文件名 = 获取文件名称 Edge浏览器下需要先定义变量、再进行赋值（不能写内联表达式）
    let fileName = decodeURIComponent(res.headers["content-disposition"].split("=")[1]);
    link.download = fileName
    // })
    let objectUrl = URL.createObjectURL(blob)
    link.href = objectUrl
    document.body.appendChild(link)
    // 下载文件
    link.click()
    // 释放内存
    window.URL.revokeObjectURL(objectUrl)
    document.body.removeChild(link)
  })
}

function handlePreview() {
}

// 覆盖默认的上传行为
function requestUpload() {
}

//移除
function handleRemove(_file, fileList) {
  fileList.value = fileList
}

// 上传文件
function uploadFile(file) {
  fileData.value.append('file', file.file) // append增加数据
}

// 选取文件超过数量提示
function handleExceed(files, fileList) {
  ElMessage.warning(
    `当前限制选择 2 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
    } 个文件`
  )
}

//监控上传文件列表
function handleChange(file, fileListInfo) {
  let existFile = fileListInfo.slice(0, fileListInfo.length - 1).find((f) => f.name === file.name)
  if (file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length) !== 'jasper' && file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length) !== 'jrxml') {
    fileListInfo.pop()
    return ElMessage.error('上传的文件类型不是.jasper,.jrxml文件，请重新上传!')
  }
  if (existFile) {
    ElMessage.error('当前文件已经存在!')
    fileListInfo.pop()
  }
  fileList.value = fileListInfo
}

// 上传到服务器
function submitUpload() {
  if (!form.value.templateType) {
    return ElMessage.error("模板类型不能为空，请选择模板类型后再上传。")
  }
  if (fileList.value.length === 0) {
    return ElMessage.warning("请先选择文件")

  }
  const isLt100M = fileList.value.every((file: any) => file.size / 1024 / 1024 < 100)
  if (!isLt100M) {
    return ElMessage.error('请检查，上传文件大小不能超过100MB!')

  }
  fileData.value = new FormData() // new formData对象
  uploadRef.value.submit() // 提交调用uploadFile函数
  fileData.value.append("templateName", form.value.templateName)
  fileData.value.append("templateCode", form.value.templateCode)
  fileData.value.append("orgId", queryParams.value.orgId)
  fileData.value.append("templateType", form.value.templateType)
  fileData.value.append("filePath", form.value.filePath)
  uploadPdfFile(fileData.value).then((response) => {
    form.value.filePath = response.data.filePath
    form.value.fileUrl = response.data.fileUrl
    ElMessage.success('上传成功')
    if (form.value.filePath.length > 0) {
      // 获取路径最后一位 路径字符串
      let lastPathIndex = Number(response.data.filePath.lastIndexOf("\\") || response.data.filePath.lastIndexOf("/")) + 1;
      // 获取路径中最后一个.
      let lastIndex = response.data.filePath.lastIndexOf(".");
      form.value.templateCode = response.data.filePath.substring(lastPathIndex, lastIndex)
    }
    fileList.value = []
  })
}

function templateTypeChange(_val) {
  // let index = dictDataMap['pdf_print_template'].findIndex(item => {
  //     return item.value === val
  // })
  // form.templateCode = dictDataMap['pdf_print_template'][index].value
}
</script>
<script lang="ts">
export default {
  name: "PrintPdfTemplate"
}
</script>
